Ruby On Rails Interview Questions and Answers
Question: What is Eager Loading in Ruby on Rails?Answer:Eager loading is a great optimization strategy to reduce the number of queries that are made against the DB. Say you are finding 10 employees and then you are looking for their post codes. Then your query would appear something like this: clients = Client.limit(10) clients.each do |client| puts client.address.postcode end This may seem fine at first look but really this implementation leaves much to be desired. It makes 11 DB calls just to get the results. Now you can optimize this query by making a slight change in the request like this: clients = Client.includes(:address).limit(10) clients.each do |client| puts client.address.postcode end This new request makes two SQL calls like this: SELECT * FROM clients LIMIT 10 SELECT addresses.* FROM addresses WHERE (addresses.client_id IN (1,2,3,4,5,6,7,8,9,10)) So, as you can see it really loads a lot more upfront and therefore it is called eager loading. |
Is it helpful?
Yes
No
Most helpful rated by users:
- What is Ruby On Rails?
- Why Ruby on Rails?
- Explain how (almost) everything is an object in Ruby.
- What are Gems and which are some of your favorites?
- How would you declare and use a constructor in Ruby?